# script calculates and plots history of the dividend yield
# and payments of a set of stock symbols

require(zoo)
require(quantmod)

symbols <- c("CY", "BIP")
from <- "1999-01-01"
to <- "2013-09-30"

for (sym in symbols) {
  # get price, dividends and splits from finance.yahoo.com
  TS <- getSymbols(sym, from=from, to=to, auto.assign=FALSE)
  div <- getDividends(sym, from=from, to=to)
  splits <- getSplits(sym, from=from, to=to)
  
  # adjust for splits: code copied and adapted from quantmod::adjustOHLC
  if (is.xts(splits) && is.xts(div) && nrow(splits) > 0 && nrow(div) > 0) {
    div <- div * 1/adjRatios(splits = merge(splits, index(div)))[, 1]
    colnames(div) <- "Dividend"
  }
  ratios <- adjRatios(splits, div, Cl(TS))
  Adjusted <- Cl(TS) * ratios[,1]
  TS <- structure(cbind((ratios[,1] * (Op(TS) - Cl(TS)) + Adjusted), 
                        (ratios[,1] * (Hi(TS) - Cl(TS)) + Adjusted), 
                        (ratios[,1] * (Lo(TS) - Cl(TS)) + Adjusted), 
                        Adjusted, 
                        if (has.Vo(TS)) Vo(TS)
                        else NULL, 
                        if (has.Ad(TS)) Ad(TS)
                        else NULL), 
                  .Dimnames = list(NULL, colnames(TS)))
  
  # assume the daily dividend "payment" to be constant within a quarter
  TSComb <- merge(Cl(TS), div, fill=0)
  DailyDiv <- structure(apply.quarterly(TSComb[,2], mean), 
                        .Dimnames = list(NULL, "DailyDividend"))
  TSComb <- na.locf(merge(TSComb, DailyDiv), fromLast=TRUE)
  TSComb <- merge(TSComb, structure(runSum(TSComb[,"DailyDividend"], n=250), 
                                    .Dimnames = list(NULL, "YearlyDividend")))
  TSComb <- merge(TSComb, structure(TSComb[,"YearlyDividend"]/TSComb[,1]*100, 
                                    .Dimnames = list(NULL, "Yield")))
  
  # plot yield and dividend payments
  plot(as.zoo(cbind(TSComb[,"Yield"], div)),
       main=paste(sym, "Dividend Yield"),
       heights=c(2,1),
       ylim=list(c(0,max(TSComb[,"Yield"], na.rm=TRUE)), 
                 c(0,max(div))),
       xlab=NULL, ylab=c("Yield", "Dividend"),
       col="blue",
       las=1, type=c("l", "p"), yax.flip=1)
}

